package org.dromara.system.controller.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.constant.CacheNames;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.mybatis.helper.DataBaseHelper;
import org.dromara.system.domain.SysDept;
import org.dromara.system.domain.SysRoleDept;
import org.dromara.system.mapper.SysDeptMapper;
import org.dromara.system.mapper.SysRoleDeptMapper;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

/**
 * @author: zhou shuai
 * @date: 2024/10/5 20:39
 * @version: v1
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/system/data/scope")
public class SysDataScopeApiController {

    private final SysRoleDeptMapper roleDeptMapper;
    private final SysDeptMapper deptMapper;

    /**
     * 获取角色自定义权限语句
     *
     * @param roleId 角色ID
     * @return 返回角色的自定义权限语句，如果没有找到则返回 null
     */
    @GetMapping("/role/custom")
    @Cacheable(cacheNames = CacheNames.SYS_ROLE_CUSTOM, key = "#roleId", condition = "#roleId != null")
    public R<String> getRoleCustom(@RequestParam("roleId") Long roleId) {
        String roleCustomId = "-1";
        if (Objects.nonNull(roleId)) {
            List<SysRoleDept> list = roleDeptMapper.selectList(
                new LambdaQueryWrapper<SysRoleDept>()
                    .select(SysRoleDept::getDeptId)
                    .eq(SysRoleDept::getRoleId, roleId));
            if (CollUtil.isNotEmpty(list)) {
                roleCustomId = StreamUtils.join(list, rd -> Convert.toStr(rd.getDeptId()));
            }
        }
        return R.ok(roleCustomId);
    }

    /**
     * 获取部门和下级权限语句
     *
     * @param deptId 部门ID
     * @return 返回部门及其下级的权限语句，如果没有找到则返回 null
     */
    @GetMapping("/dept/pers")
    @Cacheable(cacheNames = CacheNames.SYS_DEPT_AND_CHILD, key = "#deptId", condition = "#deptId != null")
    public R<String> getDeptAndChild(@RequestParam("deptId") Long deptId) {
        String deptCustomId = "-1";
        if (Objects.nonNull(deptId)) {
            List<Long> deptIds = deptMapper.selectDeptAndChildById(deptId);
            deptCustomId = CollUtil.isNotEmpty(deptIds) ? StreamUtils.join(deptIds, Convert::toStr) : "-1";
        }
        return R.ok(deptCustomId);
    }

}
